import React, { useState, useEffect } from "react";
import {
  Dialog,
  DialogContent,
  DialogTitle,
  DialogHeader,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  CheckCircle,
  AlertCircle,
  AlertTriangle,
  FileText,
  RotateCcw,
  ChevronDown,
  ChevronUp,
  Lightbulb,
  ListChecks,
  Clock,
  MapPin,
  X,
} from "lucide-react";
import { DictTypeAPI, DictDataAPI } from "@/api/dictionary";

export default function SmartRecommendationModal({
  isOpen,
  onClose,
  crossingPoint,
  recommendation,
  onSchemeCreated,
}) {
  const [expandedSteps, setExpandedSteps] = useState({});
  const [showAlternative, setShowAlternative] = useState(false);
  const [crossingTypeMap, setCrossingTypeMap] = useState({}); // 动态存储跨越类型映射
  const [loadingCrossingTypes, setLoadingCrossingTypes] = useState(true);

  // 初始化时获取跨越类型数据
  useEffect(() => {
    const fetchCrossingTypes = async () => {
      try {
        setLoadingCrossingTypes(true);
        const typeResponse = await DictTypeAPI.getList();
        const crossingType = typeResponse.rows?.find(
          (item) => item.dictName === "跨越类型"
        );

        //     // 2. 获取具体字典数据

        // 2. 通过DictDataAPI获取该类型下的所有数据

        const dataRes = await DictDataAPI.getList({
          dictType: crossingType.dictType,
        });
        const crossingDataList = dataRes.rows || [];
        // 3. 构建key-value映射（value为字典数据的名称）
        const typeMap = crossingDataList.reduce((map, item) => {
          map[item.dictValue] = item.dictLabel; // 假设dictValue是编码（如"railway"），dictLabel是显示名称
          return map;
        }, {});
        setCrossingTypeMap(typeMap);
      } catch (error) {
        console.error("获取跨越类型数据失败：", error);
        // 失败时使用默认映射兜底
        setCrossingTypeMap({});
      } finally {
        setLoadingCrossingTypes(false);
      }
    };

    if (isOpen) {
      fetchCrossingTypes();
    }
  }, [isOpen]);

  if (!recommendation) return null;

  const {
    methodTemplate,
    advantages,
    considerations,
    reasoning,
    alternativeMethods,
    confidence,
  } = recommendation;

  const confidencePercentage = Math.round((confidence || 0) * 100);
  const totalDuration = methodTemplate?.constructionSteps?.reduce(
    (sum, step) => sum + (step.durationDays || 0),
    0
  );

  // 处理方案创建
  const handleCreate = () => {
    if (methodTemplate && onSchemeCreated) {
      onSchemeCreated({
        method: methodTemplate.id,
        reasoning: reasoning,
        estimatedDuration: totalDuration,
        disadvantages: considerations,
      });
    }
  };

  // 切换步骤展开状态
  const toggleStep = (stepId) => {
    setExpandedSteps((prev) => ({
      ...prev,
      [stepId]: !prev[stepId],
    }));
  };

  // 切换备选方案显示状态
  const toggleAlternative = () => {
    setShowAlternative(!showAlternative);
  };

  // 切换到备选方案
  const handleAlternativeSelect = (alternativeMethod) => {
    if (alternativeMethod && onSchemeCreated) {
      const altTotalDuration = alternativeMethod.constructionSteps?.reduce(
        (sum, step) => sum + (step.durationDays || 0),
        0
      );
      onSchemeCreated({
        method: alternativeMethod.id,
        reasoning: `选择了备选方案: ${alternativeMethod.methodName}`,
        estimatedDuration: altTotalDuration,
        disadvantages: alternativeMethod.considerations || [],
      });
    }
  };

  // 获取显示名称（兼容未加载完成的情况）
  const getCrossingTypeName = (key) => {
    if (loadingCrossingTypes) return "加载中...";
    return crossingTypeMap[key] || key; // 未找到时显示原始key
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-4xl max-h-[90vh] overflow-hidden p-0">
        {/* 固定头部区域 */}
        <div className="sticky top-0 z-10 bg-yellow-50 p-4 flex border-b">
          <div>
            <DialogTitle className="flex items-center gap-2 text-xl font-bold text-gray-800">
              <Lightbulb className="w-5 h-5 text-blue-600" />
              智能施工方案推荐
            </DialogTitle>
            <p className="text-sm text-gray-500 mt-1">
              为 <span className="font-medium">{crossingPoint?.name}</span>{" "}
              定制的方案建议
            </p>
          </div>
        </div>

        {/* 推荐理由区域 */}
        <div className="sticky top-[84px] z-10 bg-white p-4 border-b border-gray-100">
          <h4 className="font-semibold mb-2 text-gray-700 flex items-center gap-2">
            <FileText className="w-4 h-4 text-blue-600" />
            推荐理由
          </h4>
          <p className="text-sm text-gray-600">
            {reasoning || "无推荐理由说明"}
          </p>
        </div>

        {/* 滚动内容区域 */}
        <div className="max-h-[calc(90vh-168px)] overflow-y-auto">
          <div className="p-4">
            {/* 推荐方案概览 */}
            <div className="bg-green-50 rounded-lg border border-green-200 mb-6">
              <div className="p-4">
                <div className="flex justify-between items-start mb-3">
                  <div>
                    <h3 className="text-lg font-semibold text-gray-900">
                      {methodTemplate?.methodName || "推荐施工方案"}
                    </h3>
                    <div className="flex items-center mt-1">
                      <Badge className="bg-green-100 text-green-800 hover:bg-green-200">
                        匹配度 {confidencePercentage}%
                      </Badge>
                    </div>
                  </div>
                </div>

                <div className="grid grid-cols-2 md:grid-cols-3 gap-3 text-sm mb-4">
                  <div className="flex items-center gap-1.5 text-gray-700">
                    <ListChecks className="w-4 h-4 text-gray-500" />
                    <span>
                      步骤: {methodTemplate?.constructionSteps?.length || 0}
                    </span>
                  </div>
                  <div className="flex items-center gap-1.5 text-gray-700">
                    <Clock className="w-4 h-4 text-gray-500" />
                    <span>工期: {totalDuration} 天</span>
                  </div>
                  <div className="flex items-center gap-1.5 text-gray-700">
                    <MapPin className="w-4 h-4 text-gray-500" />
                    <span>
                      适用场景:{" "}
                      {methodTemplate?.applicableScenarios?.length
                        ? getCrossingTypeName(
                            methodTemplate.applicableScenarios[0]
                          )
                        : "通用场景"}
                    </span>
                  </div>
                </div>

                <p className="text-sm text-gray-700 mb-4">
                  {methodTemplate?.description || "无方案描述"}
                </p>

                {/* 适用场景 */}
                {methodTemplate?.applicableScenarios?.length > 0 && (
                  <div className="mb-4">
                    <h6 className="font-medium text-gray-700 mb-1">适用场景</h6>
                    <div className="flex flex-wrap gap-2">
                      {methodTemplate.applicableScenarios.map(
                        (scenario, index) => (
                          <Badge
                            key={index}
                            variant="secondary"
                            className="bg-blue-50 text-blue-700"
                          >
                            {getCrossingTypeName(scenario)}
                          </Badge>
                        )
                      )}
                    </div>
                  </div>
                )}
              </div>

              {/* 方案详情标签页 */}
              <Tabs
                defaultValue="steps"
                className="w-full border-t border-green-200"
              >
                <TabsList className="grid w-full grid-cols-2">
                  <TabsTrigger value="steps">施工步骤</TabsTrigger>
                  <TabsTrigger value="analysis">方案分析</TabsTrigger>
                </TabsList>

                {/* 施工步骤 */}
                <TabsContent value="steps" className="p-4 m-0">
                  <div className="space-y-2">
                    {methodTemplate?.constructionSteps?.map((step) => (
                      <div
                        key={step.id || step.stepOrder}
                        className="border border-gray-200 rounded-md overflow-hidden"
                      >
                        <div
                          className="flex justify-between items-center p-3 bg-white cursor-pointer"
                          onClick={() => toggleStep(step.stepOrder)}
                        >
                          <div className="flex items-center">
                            <span className="bg-green-100 text-green-800 rounded-full w-6 h-6 flex items-center justify-center text-sm mr-2">
                              {step.stepOrder}
                            </span>
                            <span className="font-medium">{step.stepName}</span>
                          </div>
                          <div className="text-sm text-gray-500">
                            工期: {step.durationDays}天
                          </div>
                          {expandedSteps[step.stepOrder] ? (
                            <ChevronUp
                              size={16}
                              className="text-gray-500 ml-2"
                            />
                          ) : (
                            <ChevronDown
                              size={16}
                              className="text-gray-500 ml-2"
                            />
                          )}
                        </div>

                        {expandedSteps[step.stepOrder] && (
                          <div className="p-3 bg-gray-50 text-sm border-t border-gray-200">
                            <p className="text-gray-600 mb-3">
                              {step.description}
                            </p>

                            {/* 显示关键资源信息 */}
                            {(step.requiredEquipment?.length || 0) > 0 && (
                              <div>
                                <p className="text-xs font-medium text-gray-500 mb-1">
                                  所需设备:
                                </p>
                                <div className="flex flex-wrap gap-2">
                                  {step.requiredEquipment.map((equip, i) => (
                                    <Badge
                                      key={i}
                                      variant="secondary"
                                      className="text-xs"
                                    >
                                      {equip.name} x{equip.quantity}
                                    </Badge>
                                  ))}
                                </div>
                              </div>
                            )}
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                </TabsContent>

                {/* 方案分析 */}
                <TabsContent value="analysis" className="p-4 m-0 space-y-4">
                  <div>
                    <h4 className="font-medium text-green-700 mb-2 flex items-center gap-2">
                      <CheckCircle className="w-4 h-4" />
                      推荐优势
                    </h4>
                    <ul className="list-disc pl-5 space-y-1 text-sm text-gray-700">
                      {advantages?.map((item, index) => (
                        <li key={index} className="flex items-start">
                          <CheckCircle className="h-4 w-4 text-green-500 mr-2 mt-0.5 flex-shrink-0" />
                          <span>{item}</span>
                        </li>
                      ))}
                    </ul>
                  </div>

                  <div>
                    <h4 className="font-medium text-orange-700 mb-2 flex items-center gap-2">
                      <AlertTriangle className="w-4 h-4" />
                      注意事项
                    </h4>
                    <ul className="list-disc pl-5 space-y-1 text-sm text-gray-700">
                      {considerations?.map((item, index) => (
                        <li key={index} className="flex items-start">
                          <AlertTriangle className="h-4 w-4 text-orange-500 mr-2 mt-0.5 flex-shrink-0" />
                          <span>{item}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                </TabsContent>
              </Tabs>

              <div className="p-4 border-t border-green-200 flex justify-end">
                <Button
                  onClick={handleCreate}
                  className="bg-green-600 hover:bg-green-700"
                >
                  基于此方案创建
                </Button>
              </div>
            </div>

            {/* 备选方案 */}
            {alternativeMethods?.length > 0 && (
              <div>
                <Button
                  className="flex items-center text-gray-700 hover:text-gray-900 mb-3 bg-transparent hover:bg-gray-100 border border-gray-200 w-full justify-between"
                  onClick={toggleAlternative}
                >
                  <span className="font-medium">备选方案</span>
                  {showAlternative ? (
                    <ChevronUp size={16} />
                  ) : (
                    <ChevronDown size={16} />
                  )}
                </Button>

                {showAlternative && (
                  <div className="space-y-4">
                    {alternativeMethods.map((alt, index) => (
                      <div
                        key={index}
                        className="p-4 border border-gray-200 rounded-lg bg-gray-50"
                      >
                        <h4 className="font-medium text-gray-900">
                          {alt.alternativeMethod?.methodName}
                        </h4>
                        <p className="text-sm text-gray-600 mt-1">
                          {alt.alternativeMethod?.description || "无方案描述"}
                        </p>
                        <p className="text-sm text-amber-700 mt-2 flex items-center">
                          <AlertCircle className="w-3 h-3 inline mr-1" />
                          {alt.reason}
                        </p>

                        {/* 适用场景 */}
                        {alt.alternativeMethod?.applicableScenarios?.length >
                          0 && (
                          <div className="mt-3">
                            <p className="text-xs font-medium text-gray-500 mb-1">
                              适用场景:
                            </p>
                            <div className="flex flex-wrap gap-2">
                              {alt.alternativeMethod.applicableScenarios.map(
                                (scenario, i) => (
                                  <Badge
                                    key={i}
                                    variant="secondary"
                                    className="text-xs bg-gray-100"
                                  >
                                    {getCrossingTypeName(scenario)}
                                  </Badge>
                                )
                              )}
                            </div>
                          </div>
                        )}

                        <Button
                          variant="secondary"
                          size="sm"
                          className="mt-3 text-blue-600 hover:text-blue-800"
                          onClick={() =>
                            handleAlternativeSelect(alt.alternativeMethod)
                          }
                        >
                          <RotateCcw className="w-3 h-3 mr-1 inline" />
                          选择此方案
                        </Button>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            )}
          </div>

          {/* 底部关闭按钮 */}
          <div className="p-4 border-t border-gray-100 flex justify-end">
            <Button variant="outline" onClick={onClose}>
              关闭
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
